import { HttpService, Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import { UserPo } from './user.interface';
// var WechatAPI = require('co-wechat-api');

@Injectable()
export class UserService {
  private readonly logger = new Logger(UserService.name);

  public accessToken: string;
  public lastTokenTime: number;

  constructor(
    @InjectRepository(User)
    private readonly wechatUserRepository: Repository<User>,
    private readonly httpService: HttpService,
  ) {
    // this.fetchWechatUser();
  }
  async getToken() {
    if (
      !this.accessToken ||
      +new Date() - this.lastTokenTime >= 2 * 60 * 60 * 1000
    ) {
      await this.fetchToken();
    }
    return this.accessToken;
  }
  async fetchToken() {
    var appid = 'wx9135d3545cd793db';
    var appsecret = '83d2ee41fb837abf965ef0a184e03669';
    const res = await this.httpService
      .get(
        `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`,
      )
      .toPromise();
    const {
      data: { access_token },
    } = res;
    this.accessToken = access_token;
    this.logger.log('fetchToken', access_token);
    return access_token;
  }
  async list() {
    return await this.wechatUserRepository.find();
  }

  async add(userPo: UserPo) {
    const item = await this.wechatUserRepository.findOne(userPo.openid);
    if (item) {
      return 1;
    }
    const count = await this.wechatUserRepository.save(
      this.wechatUserRepository.create(userPo),
    );
    return count;
  }

  async fetchWechatUser() {
    let token = await this.getToken();
    const res = await this.httpService
      .get(`https://api.weixin.qq.com/cgi-bin/user/get?access_token=${token}`)
      .toPromise();
    const {
      data: {
        data: { openid },
      },
    } = res;

    openid.map(item => {
      this.add({ openid: item });
    });
  }
}
